package cn.multThread.syn;

/**
 * 生成者与消费者
 * 方法一：管程法
 * @author 67038
 *
 */
public class consumerAndProducer1 {

	public static void main(String[] args) {
		
		buffer b = new buffer();
		consumer c = new consumer(b);
		producer p = new producer(b);
		c.start();
		p.start();
	}
	
	

}
// m馒头
class mantou{
	int id;
	public mantou(int id) {
		this.id = id;
	}
}
// 馒头框 ， 缓冲区
class buffer{
	int index = 0;
	mantou ms[] = new mantou[20];
	
	public synchronized void push(mantou mt) {
		if(index==ms.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.notify();
		ms[index++] = mt;
	}
	public synchronized mantou pop() {
		if(index==0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.notify();
		return ms[--index];
	}
}

// 消费者
class consumer extends Thread{
	buffer bf = null;
	public consumer(buffer bf) {
		this.bf = bf;
	}
	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			mantou m = bf.pop();
			System.out.println("消费："+i);
		}
	}
}
// 生成者
class producer extends Thread{
	buffer bf = null;
	public producer(buffer bf) {
		this.bf = bf;
	}
	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			
			bf.push(new mantou(i));
			System.out.println("生成："+i);
		}
	}
}